/**
 * 
 */
package com.duowan.cms.intf.fahao;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.duowan.cms.common.exception.BaseCheckedException;
import com.duowan.cms.common.util.DateUtil;
import com.duowan.cms.common.util.JsonUtil;
import com.duowan.cms.common.util.NetUtil;
import com.duowan.cms.dto.gametest.GameTestInfo;
import com.duowan.cms.intf.Constants;

@Service("fahaoRemoteService")
class FahaoServiceImpl implements FahaoRemoteService {
	private static Logger logger = Logger.getLogger(FahaoServiceImpl.class);
    public FahaoInfo getByGameName(String gameName) throws BaseCheckedException, UnsupportedEncodingException {

    	String kalinkURL =  Constants.FAHAO_URL;
		
		Map<String, String> postParamsMap = new HashMap<String, String>(); 
		postParamsMap.put(Constants.FAHAO_ACTION,Constants.FAHAO_API_NEWGAME);
		postParamsMap.put("gameName", gameName);
		String data = NetUtil.postHttpRequest(postParamsMap, kalinkURL, Constants.EXPIRE_SECONDS);
		data = FahaoRankHelper.trimRepCode(data);
			logger.info(" data from " + kalinkURL + ",data:"+data);

			if (data != null) {
				List<FahaoInfo> fahaoInfos = JsonUtil.jsonString2JavaBeanList(FahaoInfo.class, data);
				FahaoInfo fahaoInfo = fahaoInfos.get(0);
				fahaoInfo.setActState(URLDecoder.decode(fahaoInfo.getActState(),"utf-8"));
				fahaoInfo.setGameName(gameName);
//				fahao.getKuUrl();
				return fahaoInfo;
			}
		
		return null;
    }

    /**
	 * 获得获取发号数据信息列表政
	 * 只支持：新游测试，网站预订排行(周月总)，网站发号排行(周月总)，游戏特权
	 * 
	 * @throws BaseCheckedException
	 */
    public Map<String, List<FahaoInfo>> getFahaoRank(String action, String gameName) throws BaseCheckedException {
    	FahaoRankHelper fahaoRankHelper = new FahaoRankHelper();
		Map<String, List<FahaoInfo>> map = null;
			if (!StringUtils.isNotBlank(action)) {
				logger.warn("action isBlank " );
				return map;
			}
			if (Constants.FAHAO_API_NEWGAME.equals(action)) {// 新游测试
				map = fahaoRankHelper.getMapFromNewGameTest(gameName);
			}else if (Constants.FAHAO_API_BOOK.equals(action)) {// 网站预订排行(周月总)
				map = fahaoRankHelper.getMap(Constants.FAHAO_API_BOOK);
			}else if (Constants.FAHAO_API_SEND.equals(action)) {// 网站发号排行(周月总)
				map = fahaoRankHelper.getMap(Constants.FAHAO_API_SEND);
			}else if (Constants.FAHAO_API_ACTIVE.equals(action)) {// 最新活动

			}else if (Constants.FAHAO_YXTQ_ACTIVE.equals(action)){
				map = fahaoRankHelper.getMap(Constants.FAHAO_YXTQ_ACTIVE);
			}else{
				logger.warn("action value no  know:" + action);
				map = fahaoRankHelper.getMap(action);
				//return map;
			}

		
		return map;
    }
    
    @Override
    public List<GameTestInfo> listSearchGameTestInfo(Map<String, String> paramsMap) {
        
        String responseData = null;
        try {
            responseData = NetUtil.getHttpRequest(paramsMap, Constants.GAMETESTINFO_URL, Constants.EXPIRE_SECONDS);
            return getListFromJson(responseData);
        } catch (Exception e) {
            logger.info("新游测试返回数据：" + responseData);
            logger.warn("获取新游戏测试信息异常：", e);
            return new ArrayList<GameTestInfo>();
        }
    }
    
    private List<GameTestInfo> getListFromJson(String responseData) throws Exception{
        
        JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(responseData);
        String code = jsonObject.getString("code");
        if(!"OK".equalsIgnoreCase(code)){
            throw new Exception("获取数据不正确！");
        }
        JSONArray dataList = jsonObject.getJSONArray("data");
        
        List<GameTestInfo> list = new ArrayList<GameTestInfo>();
        if (null != dataList && !dataList.isEmpty()) {
            for (int i=0; i<dataList.size(); i++) {
                JSONObject jsonObjecti = dataList.getJSONObject(i);
                list.add(jsonObject2GameTestInfo(jsonObjecti));
            }
        }
        return list;
    }
    
    private GameTestInfo jsonObject2GameTestInfo(JSONObject j){
        
        GameTestInfo g = new GameTestInfo();
        
        g.setId(j.getInt("gameTestId"));
        Date time = null;
        String timeStr = j.getString("time");
        try {
            time = DateUtil.parse(timeStr, DateUtil.defaultDatePatternStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        g.setTime(time);
        g.setTimeStr(timeStr);
        g.setGameName(j.getString("gameName"));
        g.setGameNameUrl(j.getString("gameNameUrl"));
        g.setState(j.getString("state"));
        g.setStateUrl(j.getString("stateUrl"));
        g.setDownload(j.getString("download"));
        g.setDownloadUrl(j.getString("downloadUrl"));
        g.setCutPictureDesc(j.getString("cutPic"));
        g.setCutPictureUrl(j.getString("cutPicUrl"));
        g.setVideoDesc(j.getString("video"));
        g.setVideoUrl(j.getString("videoUrl"));
        g.setCompany(j.getString("company"));
        g.setCompanyUrl(j.getString("companyUrl"));
        g.setDuowanChannel(j.getString("area"));
        g.setDuowanChannelUrl(j.getString("areaUrl"));
        g.setAccountDesc(j.getString("account"));
        g.setAccountUrl(j.getString("accountUrl"));
        g.setCommentDesc(j.getString("comment"));
        g.setCommentUrl(j.getString("commentUrl"));
        g.setDiy(j.getString("custom"));
        g.setIndexCheck(j.getString("checkIndex"));
        g.setPower(j.getInt("weights"));
        g.setPubCheck(j.getString("checkBeta"));
        g.setFreeGame(j.getString("freeGame"));
        g.setHasPay(j.getString("hasPay"));
        g.setAbroad(j.getString("abroad"));
        String gstatus = j.getString("gameStatus");
        if("SEAL_TEST".equals(gstatus)){
            g.setGstatus("1");
        }else if("ALPHA_TEST".equals(gstatus)){
            g.setGstatus("2");
        }else if("BETA_TEST".equals(gstatus)){
            g.setGstatus("3");
        }else {
            g.setGstatus("1");
        }
        
        //新增发号信息
        g.setGameId(j.getInt("gameId"));
        g.setTqzxUrl(j.getString("tqzxUrl"));
        g.setActState(j.getString("actState"));
        
        return g;
    }



}
